package com.linbei.linbei_movie.controller;

import com.linbei.linbei_movie.pojo.Result;
import com.linbei.linbei_movie.pojo.User;
import com.linbei.linbei_movie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/findById/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        System.out.println("getUserById"+id);
        User user = userService.getUserById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    @RequestMapping("/registered")
    public Result<Integer> addUser(@RequestBody User user) {

        User existingUser = userService.getUserByUsername(user.getUsername());
//        System.out.println(user.getUsername());
//        System.out.println(existingUser);
        if (existingUser != null) {
//            System.out.println(111111);
            return Result.error("用户名已存在");
        }
        return Result.success(userService.addUser(user));
    }

    @RequestMapping("/login")
    public Result<User> login(@RequestBody User user) {
//        System.out.println(user.toString());
        //根据前端传来的用户名查询数据库
        User existingUser = userService.getUserByUsername(user.getUsername());
        if (existingUser == null) {
            return Result.error("用户名不存在");
        }
        //判断密码是否正确
        if (!existingUser.getPassword().equals(user.getPassword())) {
            return Result.error("密码错误");
        }
        return Result.success(userService.login(user));
    }

    //用户信息修改
    @RequestMapping("/update")
    public Result<User> updateUser(@RequestBody User user) {

//        System.out.println(user.toString());
        userService.updateUser(user);
        User newUser = userService.getUserById(user.getUserId());
//        System.out.println(newUser.toString());
        return Result.success(newUser);
    }
}
